package cn.wolfcode.luowowo.wensite.util;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.wensite.web.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户对象解析器
 * 将cookie中token值解析成userinfo对象,并注入到请求映射方法中
 */
public class UserInfoArgunmentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    /**
     * 该解析器支持解析参数的参数类型
     * 该方法可以设置支持userinfo的支持类型
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * 如果上面的supportsParameter返回值为true,那么表示解析器启动,开始解析对应的参数
     * 该解析方法是将token转化为userinfo对象
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse resp = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String token = CookieUtil.getCookie(req);
        return userInfoRedisService.getToken(token);
    }
}
